package com.spark.incoicings.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spark.incoicings.dao.CustomerMapper;
import com.spark.incoicings.dao.OrderDetailMapper;
import com.spark.incoicings.dao.ProductMapper;
import com.spark.incoicings.dao.SalesOrderMapper;
import com.spark.incoicings.service.DictTypeService;
import com.spark.incoicings.service.OrderDetailService;
import com.spark.incoicings.vo.CustomerVO;
import com.spark.incoicings.vo.DictVO;
import com.spark.invoicings.entity.OrderDetail;
import com.spark.invoicings.entity.Product;
import com.spark.invoicings.entity.SaleCustomer;
import com.spark.invoicings.entity.SalesOrder;
import com.spark.invoicings.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/login")
@Slf4j
public class OrderDetailController {
    @Resource
    private OrderDetailService orderDetailService;
    @Resource
    private DictTypeService dictTypeService;
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Resource
    private ProductMapper productMapper;
    @GetMapping("/selectOrderDetails")
    public Result selectOrderDetails(@RequestParam(defaultValue = "1")Integer pageNum,
                                     @RequestParam(defaultValue = "3")Integer pageSize,
                                     @RequestParam(required = false)String code){
        PageHelper.startPage(pageNum,pageSize);
        List<OrderDetail> orderDetails = orderDetailService.selectOrderDetails(code);
        orderDetails.forEach(orderDetail -> {
            log.info("orderDetail={}",orderDetail);
            Product product = productMapper.selectById(orderDetail.getProductId());
            orderDetail.setProducts(product);
            SalesOrder salesOrder = salesOrderMapper.selectById(orderDetail.getSalesOrderId());
            orderDetail.setSalesOrder(salesOrder);
            DictVO status = dictTypeService.selectDictTow(orderDetail.getSalesOrder().getOrderId());
            log.info("status={}",status);
            orderDetail.getSalesOrder().setStatus(status.getStatus());
            SaleCustomer saleCustomer = customerMapper.selectById(orderDetail.getSalesOrder().getCustomerId());
            orderDetail.getSalesOrder().setCustomer(saleCustomer);
            CustomerVO customerVO = customerMapper.selectCustomerVo(saleCustomer.getCustomerId());
            saleCustomer.setCustomerRating(customerVO.getCustomerRating());
            saleCustomer.setCustomerSource(customerVO.getCustomerSource());
            saleCustomer.setBillingMethod(customerVO.getBillingMethod());
        });
        PageInfo<OrderDetail> pageInfo = new PageInfo<>(orderDetails);
        return Result.success(200,"success",pageInfo);
    }
    @PostMapping("/saveOrderDetail")
    @Transactional
    public Result saveOrderDetail(@RequestBody OrderDetail detail){
        double countPrice = 0.00;//总金额
        double totalProfit = 0.00;//总利润
        double totalCost = 0.00;//总成本
        orderDetailMapper.insert(detail);
        SalesOrder salesOrder = salesOrderMapper.selectById(detail.getSalesOrderId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("sales_order_id", salesOrder.getOrderId()));
        salesOrder.setOrderDetail(orderDetails);
        for (OrderDetail orderDetail: salesOrder.getOrderDetail()){
            //销售订单id
            orderDetail.setSalesOrderId(salesOrder.getOrderId());
            //订单明细总额
            orderDetail.setSubtotalAmount(orderDetail.getQuantityOrdered()*orderDetail.getDiscountedPrice());
            //统计销售总金额
            countPrice+=orderDetail.getSubtotalAmount();
            //订单明细商品成本
            orderDetail.setProductCost(orderDetail.getCostPrice()*orderDetail.getQuantityOrdered());
            //统计总成本
            totalCost+=orderDetail.getProductCost();
            //待申请发货数量
            orderDetail.setPendingShipmentQuantity(orderDetail.getQuantityOrdered());
            //待收金额
            orderDetail.setPendingPaymentAmount(orderDetail.getSubtotalAmount());
            orderDetailMapper.updateById(orderDetail);
            Product products = productMapper.selectById(orderDetail.getProductId());
            orderDetail.setProducts(products);
        }
        salesOrder.setOrderTotalAmount(countPrice);
        totalProfit = countPrice-totalCost;
        salesOrder.setTotalProfit(totalProfit);
        salesOrder.setTotalCostOfGoods(totalCost);
        double profitPercentage = (totalProfit / countPrice) * 100;
        salesOrder.setOrderGrossMargin(profitPercentage);
        salesOrder.setPendingCollectionAmount(countPrice);
        salesOrder.setSalesCommission(countPrice*(3.0/100));
        salesOrderMapper.updateById(salesOrder);
        Product product = productMapper.selectById(detail.getProductId());
        detail.setProducts(product);
        detail.setSalesOrder(salesOrder);
        OrderDetail orderDetail = orderDetailMapper.selectById(detail.getOrderDetailId());
        return Result.success(200,"success",orderDetail);
    }
    @GetMapping("/selectOrderDetail")
    public Result selectOrderDetail(Integer id){
        OrderDetail orderDetail = orderDetailMapper.selectById(id);
        SalesOrder salesOrder = salesOrderMapper.selectById(orderDetail.getSalesOrderId());
        DictVO dictTow = dictTypeService.selectDictTow(salesOrder.getOrderId());
        salesOrder.setStatus(dictTow.getStatus());
        orderDetail.setSalesOrder(salesOrder);
        Product product = productMapper.selectById(orderDetail.getProductId());
        DictVO dictVO = productMapper.selectProductUnIt(product.getProductId());
        product.setD2Label(dictVO.getStatus());
        orderDetail.setProducts(product);
        return Result.success(200,"success",orderDetail);
    }
    @PostMapping("/updateOrderDetail")
    public Result updateOrderDetail(@RequestBody OrderDetail detail){
        double countPrice = 0.00;//总金额
        double totalProfit = 0.00;//总利润
        double totalCost = 0.00;//总成本
        orderDetailMapper.updateById(detail);
        SalesOrder salesOrder = salesOrderMapper.selectById(detail.getSalesOrderId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("sales_order_id", salesOrder.getOrderId()));
        salesOrder.setOrderDetail(orderDetails);
        for (OrderDetail orderDetail: salesOrder.getOrderDetail()){
            //销售订单id
            orderDetail.setSalesOrderId(salesOrder.getOrderId());
            //订单明细总额
            orderDetail.setSubtotalAmount(orderDetail.getQuantityOrdered()*orderDetail.getDiscountedPrice());
            //统计销售总金额
            countPrice+=orderDetail.getSubtotalAmount();
            //订单明细商品成本
            orderDetail.setProductCost(orderDetail.getCostPrice()*orderDetail.getQuantityOrdered());
            //统计总成本
            totalCost+=orderDetail.getProductCost();
            //待申请发货数量
            orderDetail.setPendingShipmentQuantity(orderDetail.getQuantityOrdered());
            //待收金额
            orderDetail.setPendingPaymentAmount(orderDetail.getSubtotalAmount());
            orderDetailMapper.updateById(orderDetail);
            Product products = productMapper.selectById(orderDetail.getProductId());
            orderDetail.setProducts(products);
        }
        salesOrder.setOrderTotalAmount(countPrice);
        totalProfit = countPrice-totalCost;
        salesOrder.setTotalProfit(totalProfit);
        salesOrder.setTotalCostOfGoods(totalCost);
        double profitPercentage = (totalProfit / countPrice) * 100;
        salesOrder.setOrderGrossMargin(profitPercentage);
        salesOrder.setPendingCollectionAmount(countPrice);
        salesOrder.setSalesCommission(countPrice*(3.0/100));
        salesOrderMapper.updateById(salesOrder);
        Product product = productMapper.selectById(detail.getProductId());
        DictVO dictVO = productMapper.selectProductUnIt(product.getProductId());
        product.setD2Label(dictVO.getStatus());
        detail.setProducts(product);
        detail.setSalesOrder(salesOrder);
        OrderDetail orderDetail = orderDetailMapper.selectById(detail.getOrderDetailId());
        return Result.success(200,"success",orderDetail);
    }
    /**
     * 根据销售订单id查出所有订单明细
     */
    @GetMapping("/selectOrderDetailByOrderId")
    public Result selectOrderDetailByOrderId(Integer id){
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>()
                                                          .eq("sales_order_id", id));
        orderDetails.forEach(orderDetail -> {
            SalesOrder salesOrder = salesOrderMapper.selectById(orderDetail.getSalesOrderId());
            orderDetail.setSalesOrder(salesOrder);
            Product product = productMapper.selectById(orderDetail.getProductId());
            orderDetail.setProducts(product);
        });
        return Result.success(200,"success",orderDetails);
    }
}
